
function Als(options) {
  if (!(this instanceof Als)) {
    return new Als(options)
  }
  options = options || {}

  // if (!options.appKey || !options.secretKey) {
  //   throw new Error('appKey and secretKey are necessary!')
  // }


  this.url= options.url || 'https://gw-api.pinduoduo.com/api/router'
  this.api={
    "stocks": "favor/stocks",
    "getuser":'_User',
    'getDetail':'favor/stocks',
    'getCouponDetail':'/favor/users/{openid}/coupons/{coupon_id}',
    'getUserCoupon':'/favor/{openid}/coupons',
    'addCounpon':'/favor/users/{openid}/coupons',
    'addLike':'/favor/like'
  }
}
let D = ['stocks','getuser','getDetail','addCounpon','getUserCoupon','addLike']


Als.prototype.request = function (params,request='POST') {
  const { method,url, ...rest } = params
  const args = {
    // timestamp: this.timestamp(),
  }

  let obj2 = Object.assign(args,rest);
  return new Promise((resolve, reject) => {
   var sendHost=''
  if(params.url){
    sendHost=params.url
  }else{
    sendHost=this.url+method
  }

    let a={
      "X-Bmob-Master-Key":"rlCbNo9RgKWxG40MJU6Nh0amB2hsKRqb",

    }
    wx.request({
      url: sendHost,
      method:request,
      data: obj2,
      header:a,
      success: res => {
    
        if (res.statusCode == 200) {
        
          if(res.data.code==200){
            resolve(res.data.data);
          }else{
        
            resolve(res.data)
          }
         
        } else {
        
          reject(res);
        }
      },
      fail: e => {
        reject(e)
      }
    })
   
  })
}

Als.prototype.execute = function (apiname, params,request='POST') {
  params.method = apiname
  return this.request(params,request).then((res) => {
    if (res) {
      return res
    } else {
      return []
      console.log('没有数据')
    }

  })
  // const field = `${apiname.replace(/\./g, '_')}_response`
  // const resp = res[field];
  // console.log("结果 -")
  // console.log(resp)

  // return this.request(params)
}



Als.prototype.funcWhere=function(){
  var errs = new Error().stack
  console.log(errs)
  var names = new Error().stack.match(/at (.*?) /g);
  var name = names[1].replace('at Object.', '').trim();
  return name;
}

for (let i = 0; i < D.length; i++) {
  !function (e) {

    Als.prototype[e] = function (data={},request='POST') {
      let method = this.api[e]
   
      if (method){
        return this.execute(method,data,request)
      }

    };

  }(D[i])

}
Als.prototype.timestamp = function (d, options) {
  d = d || new Date()
  let timestamp = d.getTime();

  return timestamp;
}

module.exports = Als